//===============================================================================
// Microsoft patterns & practices
// Mobile Client Software Factory - July 2006
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom;
using System.Reflection;
using System.IO;
using System.CodeDom.Compiler;
using System.Diagnostics;

namespace Microsoft.Practices.ObjectBuilder.ObGen
{
	/// <summary>
	/// This custom <see cref="CodeTypeReference"/> fixes a number of issues with CodeDom 
	/// type references (related to ref/out types, generics and nested types).
	/// </summary>
	[Serializable]
	public class SafeCodeTypeReference : CodeTypeReference
	{
		public SafeCodeTypeReference(Type type) : base(new SafeType(type)) { }

		class SafeType : TypeDelegator
		{
			public SafeType(Type delegatingType)
				: base(delegatingType)
			{
			}

			public override string FullName
			{
				get
				{
					if (base.typeImpl.IsGenericParameter)
					{
						return base.typeImpl.Name;
					}
					else
					{
						Type refType = base.typeImpl;
						while (refType.HasElementType)
						{
							refType = refType.GetElementType();

							if (refType.IsGenericParameter)
								return refType.Name;
						}
					}

					string typeName = base.typeImpl.FullName;

					if (typeName == null)
					{
						typeName = base.typeImpl.Namespace + "." + base.typeImpl.Name;
					}

					// Workaround bug: http://lab.msdn.microsoft.com/ProductFeedback/viewFeedback.aspx?feedbackId=FDBK50901
					if (typeName.EndsWith("&"))
					{
						typeName = typeName.Substring(0, typeName.Length - 1);
					}

					// Workaround bug: http://lab.msdn.microsoft.com/ProductFeedback/viewFeedback.aspx?FeedbackId=353e9082-d80e-48c1-a2c1-5d3aa56c1a5e
					typeName = typeName.Replace("+", ".");

					return typeName;
				}
			}
		}
	}
}
